<?php

namespace App\Console\Commands;

use App\Library\Logger;
use App\Models\CityModel;
use Illuminate\Console\Command;

class ModifyGuangdongZones extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'modify:guangdong_zones';
    private $logger;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '修复广东区域缺失数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->logger = new Logger('modify/guangdong_zones');
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $bench = new \Ubench();
        $bench->start();

        $this->action();

        $bench->end();
        $this->logger->debug("time used: " . $bench->getTime());
        $this->logger->debug("memory used: " . $bench->getMemoryUsage());
    }

    private function action()
    {
        $file = resource_path('data/zones/') . 'dg_zs.json';
        if (!is_file($file)) {
            $this->logger->error("JSON文件不存在，请检查");
            return;
        }
        $data = json_decode(file_get_contents($file), true);
        if (!$data) {
            $this->logger->error("JSON无数据，请检查");
            return;
        }
        foreach ($data as $item) {
            $this->logger->info("导入数据: " . $item['name']);
            $cityDb = CityModel::query()
                ->where('pid', '=', $item['pid'])
                ->where('level', '=', $item['level'])
                ->where('name', '=', $item['name'])
                ->first();
            if (empty($cityDb)) {
                $cityDb = new CityModel();
            }
            $cityDb->fill($item);
            $cityDb->saveOrFail();
        }
    }
}
